<?php
/**
 * Created by PhpStorm.
 * User: gxk
 * Date: 2019/4/16
 * Time: 21:59
 */

namespace Index;
use Illuminate\Database\Capsule\Manager as DB;
use Library\Queue;
defined('slim') or exit('访问不合法');
class ChatController
{
    public function __construct()
    {
    }
    /*
     * 插入聊天记录表
     */
    public function chat($request,$response,$args)
    {
        $post = $request->getParsedBody();
        $content = htmlspecialchars($post['content']);
        $data = [
            'chat_content'=>$content,
            'chat_user_id'=>$_SESSION['member_id'],
            'chat_user_name'=>$_SESSION['member_name'],
            'rece_user_id'=>$post['uid']?:0,
            'add_time'=>time(),
            'chat_ip'=>getIp(),
            'chat_read_status'=>'0',
            'chat_area'=>'',
            'chat_city'=>'',
        ];
        $send_args = [
            'method'=>'chat',
            'args'=>$data
        ];
        $res = Queue::add($send_args);
        if(!$res){
            return $response->write(JSON(255));
        }
        //内部推送消息
        $data['add_time'] = date('Y-m-d H:i:s',$data['add_time']);
        $res = curl('172.27.0.6:9502',$data,1);
        $res = json_decode($res,1);
        if ($res['status'] == 200) {
            $response->write(JSON(200,'',$data));
        } else {
            $response->write(JSON(255));
        }

    }
    /*
     * 获取聊天记录
     */
    public function chatlist($request,$response,$args)
    {
        $get = $request->getQueryParams();
        $page = isset($get['page'])?intval($get['page']):10;
        $pn = isset($get['pn'])?intval($get['pn']):1;
        $start = ($pn-1)*$page;
        //判断是群聊还是单聊
        $condition = [];
        if ($get['uid']>0) {
            $reveId = intval($get['uid']);
            $sendId = intval($request->getCookieParam('member_id'));
            $condition = function($query) use ($reveId,$sendId) {
                $query->where([
                    ['rece_user_id',$reveId],
                    ['chat_user_id',$sendId],
                ])->orwhere([
                    ['rece_user_id',$sendId],
                    ['chat_user_id',$reveId],
                ]);
            };
        } else {
            $condition[] = ['rece_user_id',0];
        }
        $list = DB::table('chat')->where($condition)->orderBy('chat_id','desc')->offset($start)->limit($page)->get()->toArray();
        $list = array_reverse($list);
        if($list){
            foreach($list as $k=>$v){
                $v->add_time = date('Y-m-d H:i:s',$v->add_time);
            }
            $response->getBody()->write(JSON(200,'',$list));
        }else{
            $response->getBody()->write(JSON(200));
        }
    }
}